<script>
  import { describe } from '$lib';
  import { Glyph } from '$lib/components';
  import { hasComponent } from '$lib/ecs';
  import { getPlayer } from '$lib/player';
  import { getPos2, hasPos2 } from '$lib/pos2';
  import { getPos3, hasPos3 } from '$lib/pos3';
  import { decode } from '$lib/util';

  const debug = false; // TODO: use global debug
  let { item, world, onclick, selected, zoomlevel } = $props();
  let selectedClass = $derived(item === selected ? 'selected' : '');
  let emptyClass = $derived((!debug && !hasComponent(world, Glyph, item)) ? 'empty' : '');
  let pc = $derived(getPlayer(world));
  let style = $derived(zoomlevel ? `font-size: ${zoomlevel*0.6}px` : '');

  const describeDirection = (e) => {
    let xy, pov;
    if (hasPos2(world, e)) {
      xy = getPos2(e);
      pov = getPos2(pc);
    } else if (hasPos3(world, e)) {
      xy = getPos3(e);
      pov = getPos3(pc);
    } else {
      return;
    }
    const {x, y} = xy;
    const dx = x - pov.x;
    const dy = y - pov.y;
    if (dx === 0 && dy === 0) {
      return '.';
    } else if (Math.abs(dx) > Math.abs(dy)*2) {
      // TODO: better math (HINT: trig)
      return (dx > 0) ? '>' : '<';
    } else if (Math.abs(dy) > Math.abs(dx)*2) {
      return (dy > 0) ? 'v' : '^';
    } else {
      if (dx > 0) {
        return ((dy > 0) ? 'v' : '^') + '>';
      } else {
        return '<' + ((dy > 0) ? 'v' : '^');
      }
    }
  };
</script>

<div class="envitem {selectedClass} {emptyClass}" onclick={() => onclick(item)}>
  <pre class="glyph" style="{style}; color: {decode(Glyph.color[item])};">{decode(Glyph.glyph[item])} </pre>
  <span {style}>
    {describe(world, item)}
  </span>
  <span class="overlay" {style}>
    {describeDirection(item)}
  </span>
</div>

<style>
  .envitem {
    display: flex;
    justify-content: space-between;
  }

  .overlay {
    margin-left: auto;
  }

  .empty {
    display: none;
  }
</style>
